import React, { useState, useEffect } from 'react';
import { Card, Input, Button, Modal, Form, message, Row, Col } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { getAiPapers, addAiPapers, updateAiPapers, AiPapersItem } from '@/services/aiPapersService';
import { getStoredUserInfo } from '@/utils/auth';

const { TextArea } = Input;

const AiPapers: React.FC = () => {
  // 状态定义
  const [list, setList] = useState<AiPapersItem[]>([]);
  const [searchTitle, setSearchTitle] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentItem, setCurrentItem] = useState<AiPapersItem | null>(null);
  const [form] = Form.useForm();

  // 获取列表数据
  const fetchList = async () => {
    try {
      const res = await getAiPapers({ title: searchTitle });
      if (res.code === 200) {
        setList(res.data);
      }
    } catch (error) {
      message.error('获取数据失败');
    }
  };

  useEffect(() => {
    fetchList();
  }, [searchTitle]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchTitle(value);
  };

  // 处理新增/编辑提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const currentUser = getStoredUserInfo();

      if (!currentUser?.englishName) {
        message.error('获取当前用户信息失败');
        return;
      }

      if (currentItem?.id) {
        // 编辑
        const res = await updateAiPapers(currentItem.id, {
          ...values,
          updater: currentUser.englishName
        });
        if (res.code === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchList();
        }
      } else {
        // 新增
        const res = await addAiPapers({
          ...values,
          creater: currentUser.englishName
        });
        if (res.code === 200) {
          message.success('添加成功');
          setModalVisible(false);
          fetchList();
        }
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 查看详情
  const handleViewDetail = (item: AiPapersItem) => {
    setCurrentItem(item);
    setDetailVisible(true);
  };

  // 编辑项目
  const handleEdit = () => {
    form.setFieldsValue(currentItem);
    setDetailVisible(false);
    setModalVisible(true);
  };

  // 新增项目
  const handleAdd = () => {
    setCurrentItem(null);
    form.resetFields();
    setModalVisible(true);
  };

  return (
    <div className="p-6">
      {/* 顶部工具栏 */}
      <div className="mb-6 flex justify-between">
        <Input.Search
          placeholder="请输入标题搜索"
          allowClear
          enterButton={<SearchOutlined />}
          onSearch={handleSearch}
          style={{ width: 300 }}
        />
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新增
        </Button>
      </div>

      {/* 卡片列表 */}
      <Row gutter={[16, 16]}>
        {list.map((item) => (
          <Col xs={24} sm={12} md={8} lg={6} key={item.id}>
            <Card
              hoverable
              className="h-full"
              onClick={() => handleViewDetail(item)}
            >
              <h3 className="text-lg font-bold mb-2">{item.title}</h3>
              <div className="border-t border-b py-2 my-2">
                <p className="text-gray-600">{item.descript}</p>
              </div>
              <a
                href={item.urlAddress}
                target="_blank"
                rel="noopener noreferrer"
                onClick={(e) => e.stopPropagation()}
                className="text-blue-500 hover:text-blue-700"
              >
                {item.urlAddress}
              </a>
            </Card>
          </Col>
        ))}
      </Row>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={currentItem ? '编辑论文内容' : '新增论文内容'}
        open={modalVisible}
//         onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        footer={
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
            <Button key="cancel" onClick={() => setModalVisible(false)}>
              取消
            </Button>
            <Button key="submit" type="primary" onClick={handleSubmit}>
              确认
            </Button>
          </div>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>
          <Form.Item
            name="descript"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <TextArea rows={4} placeholder="请输入描述" />
          </Form.Item>
          <Form.Item
            name="urlAddress"
            label="URL地址"
            rules={[{ required: true, message: '请输入URL地址' }]}
          >
            <Input placeholder="请输入URL地址" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 详情弹窗 */}
      <Modal
        title="论文内容详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
            <Button key="edit" type="primary" onClick={handleEdit}>
              编辑
            </Button>
            <Button key="close" onClick={() => setDetailVisible(false)}>
              关闭
            </Button>
          </div>
        }
      >
        {currentItem && (
          <div>
            <h3 className="text-lg font-bold mb-4">{currentItem.title}</h3>
            <p className="mb-4">{currentItem.descript}</p>
            <a
              href={currentItem.urlAddress}
              target="_blank"
              rel="noopener noreferrer"
              className="text-blue-500 hover:text-blue-700"
            >
              {currentItem.urlAddress}
            </a>
            <div className="mt-4 text-gray-500 text-sm">
              <p>创建人：{currentItem.creater}</p>
              <p>创建时间：{currentItem.createTime}</p>
              {currentItem.updater && (
                <>
                  <p>更新人：{currentItem.updater}</p>
                  <p>更新时间：{currentItem.updateTime}</p>
                </>
              )}
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AiPapers;